﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace UniSenderSample.Controllers
{
    public class UniSenderController : ApiController
    {
        public object GetLists(string lang, string key)
        {
            var client = new UniSender.Client(lang, key) { TestMode = true };
            object error = null;
            client.OnException += e => {
                error = new {
                    error = e.Exception.Message,
                    code = "EXCEPTION"
                };
            };
            client.OnError += e => {
                error = new {
                    error = e.Error,
                    code = e.Code
                };
            };
            object result = client.GetLists();
            return error ?? result;
        }

        public object PostList(string lang, string key, int id, string title)
        {
            var client = new UniSender.Client(lang, key) { TestMode = true, MuteExceptions = false };
            try
            {
                client.UpdateList(id, title);
                return new object();
            }
            catch (UniSender.UniSenderErrorException error)
            {
                return new
                {
                    error = error.Error,
                    code = error.Code
                };
            }
            catch (Exception exc)
            {
                return new
                {
                    error = exc.Message,
                    code = "EXCEPTION"
                };
            }
        }

        public object PutList(string lang, string key, string title)
        {
            var client = new UniSender.Client(lang, key) { TestMode = true };
            try
            {
                return client.Call<object>("createList", new Dictionary<string, object>() {
                    { "title", title }
                });
            }
            catch (UniSender.UniSenderErrorException error)
            {
                return new {
                    error = error.Error,
                    code = error.Code
                };
            }
            catch (Exception exc)
            {
                return new {
                    error = exc.Message,
                    code = "EXCEPTION"
                };
            }
        }
    }
}
